/*
 * Copyright (C) 2009 CodeWerkz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.codewerkz.prompty;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * SlidesList: Shows the list of slides for a particular presentation.
 * 
 * @author ChaZ
 */
public class SlidesList extends ListActivity {

	// Database stuff.
	private SlidesDbAdapter mDbHelper;
	private Long mRowId;
	public static String PRESID = "presid";
	
	// Activities
	private final int ACTIVITY_SLIDES = 0;
	private final int ACTIVITY_EDIT = 1;
	private final int ACTIVITY_CREATE = 2;
	private final int ACTIVITY_HELP_SLIDES = 3;
	
	// Context menu stuff.
	private final int SLIDESHOW_ID = Menu.FIRST ;
	private final int EDIT_ID = Menu.FIRST +1;
	private final int DELETE_ID = Menu.FIRST + 2;
	
	//private final String TAG = "Prompty - SlList";
	
	/**
	 * Runs this function when the Activity is started.
	 * 
	 * @return void
	 */
	@Override 
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    // Load layout.
	    setContentView(R.layout.slides);
	    
	    // Create and open database.
        mDbHelper = new SlidesDbAdapter(this);
        mDbHelper.open();
        
        // Get bundle.
        mRowId = savedInstanceState != null ? savedInstanceState.getLong(PresentationsDbAdapter.KEY_ROWID) 
				: null;

        // If no existing data is present, grab the bundle.
        if (mRowId == null) {
        	Bundle extras = getIntent().getExtras();            
        	mRowId = extras != null ? extras.getLong(PresentationsDbAdapter.KEY_ROWID) 
        							: null;
        }
        
		// By this point, if the row id is null then the screen may have been turned.
		// Get the data from our future self.
		final Object data = getLastNonConfigurationInstance();
		// Check if the future self data isn't null.
		if ( data != null ) {
			// Set up us our row ID.
			this.mRowId = (Long) data;
		}
        
        // Fill the layout data.
        fillData();
        registerForContextMenu(getListView());
	}
	
	
	/**
	 * Fills up the list with the data from the sqlite3 database.
	 * 
	 * @return void
	 */
	protected void fillData() {
		// Set up a cursor to all slides from a particular presentation.
        Cursor presCursor = mDbHelper.fetchAllSlides(mRowId);
        startManagingCursor(presCursor);
        
        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{SlidesDbAdapter.KEY_STITLE, SlidesDbAdapter.KEY_STEXT};
        
        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.slidesList_title};
        
        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter pres = 
        		new SimpleCursorAdapter(this, R.layout.slides_row, presCursor, from, to);
        setListAdapter(pres);
		
	}
	
	/**
	 * Runs when our screen is rotated.
	 * 
	 * @return Object Object containing a Long that needs to be cast containing the Row Id.
	 */
    @Override
    public Object onRetainNonConfigurationInstance() {
    	// Create and initialise row id.
    	long rowId = 0;
    	// If the member row id isn't null AND isn't 0...
    	if ( mRowId != null && mRowId != 0) {
    		// Set the variables.
    		rowId = mRowId;	
    	}
    	// return row id object.
    	return rowId;
    }
	
    /**
     * Runs when the user clicks on an item in the list.
     * 
     * @param l ListView Id
     * @param v View id
     * @param position Position of item.
     * @param id ID of item.
     * @return void
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        
		// Start the slideshow.
		startSlideShow(id, mRowId);
    }
	
    /**
     * Starts the Create Slide Procedure.
     * 
     * @return void
     */
    private void createSlide() {
    	// Create a new intent and sent the id of the 
    	// presentation to the create activity.
        Intent i = new Intent(this, SlideEdit.class);
        i.putExtra(PRESID, mRowId.toString());
        startActivityForResult(i, ACTIVITY_CREATE);
    }
    
    /**
     * Runs when the Context Menu is created (Loaded).
     * 
     * @param menu Menu to create.
     * @param v View
     * @param menuInfo menuInfo 
     * @return void
     */
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		// Add in all the menu items.
		menu.setHeaderTitle("Select an action.");
	    menu.add(0, SLIDESHOW_ID, 0, R.string.slides_cmenu_startSlideshow);
		menu.add(0, EDIT_ID, 0, R.string.slides_cmenu_editSlide);
        menu.add(0, DELETE_ID, 0, R.string.slides_cmenu_deleteSlide);
	}
    
    /**
     * Runs when an item in the Context Menu is selected.
     * 
     * @param item ID of MenuItem selected.
     * @return boolean
     */
    @Override
	public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	
    	// Switch in the item ID selected through each case.
		switch(item.getItemId()) {
			case SLIDESHOW_ID:
				// Start the slideshow.
				startSlideShow(info.id, mRowId);
				return true;
		
	    	case DELETE_ID:
	            // Delete the presentation and then delete the slide using the same ID.
		        mDbHelper.deleteSlide(info.id);
		        // Refill the list.
		        fillData();
		        // Close the adapter and return true.
		        return true;
		        
			case EDIT_ID:
				// Create an intent and send it to the create activity.
		        Intent j = new Intent(this, SlideEdit.class);
		        j.putExtra(SlidesDbAdapter.KEY_ROWID, info.id);
		        startActivityForResult(j, ACTIVITY_EDIT);
				return true;
    	}
		
		return super.onContextItemSelected(item);
	}
    
    /**
     * Runs when the Menu button is pressed.
     * 
     * @param Menu to make
     * @return boolean
     */
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.slides_list_options, menu);
    	return true;
    }

    /**
     * Runs when the user selects a button from the Menu.
     * 
     * @param item Item selected.
     * @return boolean
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case R.id.slidesList_newSlide:
	        	createSlide();
	            return true;
	        case R.id.slidesList_help:
	        	showHelp();
	        	return true;
        }
        return false;
    }
    
    /**
     * Runs when the Activity is about to be destroyed for Garbage Collection.
     * 
     * @returns void
     */
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	// Prevents database leak
    	mDbHelper.close();
    }
	
    /**
     * Shows the Help screen.
     * 
     * @return void
     */
    private void showHelp() {
    	Intent i = new Intent (this, Help.class);
    	i.putExtra("helpPage", 2);
    	this.startActivityForResult(i, ACTIVITY_HELP_SLIDES);
    }
    
	/**
	 * Starts the slideshow Activity
	 *     
	 * @param slideId Slide ID to start from.
	 * @param presId Presentation ID to start from.
	 */
    private void startSlideShow(long slideId, long presId) {
    	//Create an intent and start the presentation.
		Intent i = new Intent (this, SlidesShow.class);
		i.putExtra("slideID", slideId);
		i.putExtra("presID", presId);
		startActivityForResult(i, ACTIVITY_SLIDES);
		return;
    }
    
}
